'use strict'

import axios from 'axios'
import qs from 'qs'
import {baseUrl} from './baseUrl'
import {eventBus} from '../tool/events-bus'
import {clearCookie} from '@/config/mUntils'

axios.defaults.withCredentials = true
axios.interceptors.request.use(config => {
  // let warehouseId = ~~getStore('warehouseId')
  config.headers.common['warehouseId'] = 1
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response) {
  if (response && response.data.resultCode === 3002) {
    eventBus.$message('您的登录信息已过期,请重新登录')
    clearCookie('Token')
    clearCookie('Exam')
    clearCookie('username')
    let location = window.location.origin
    window.open(`${location}/#/login`, '_self')
    return response
  }
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
  }
  // 异常状态下，把错误信息返回去
  return {
    resultCode: -505,
    resultMsg: '网络异常'
  }
}

function checkCode (res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.resultCode === -505) {
    console.log(res.resultMsg)
  }
  return res
}
// 150000 , warehouseId = ''
// headers: {
//   'warehouseId': warehouseId
// },
export default {
  post (url, data) {
    let source = axios.CancelToken.source()
    return axios({
      method: 'post',
      baseURL: baseUrl,
      url,
      data: qs.stringify(data),
      timeout: 150000,
      cancelToken: source.token
    }).then(response => {
      return checkStatus(response)
    }).then(response => {
      return checkCode(response)
    }).catch(err => {
      console.log('错误')
      source.cancel(err)
    })
  },
  filepost (url, data) {
    return axios({
      method: 'post',
      baseURL: baseUrl,
      url,
      data: data,
      timeout: 10000,
      headers: {'Content-Type': 'multipart/form-data'}
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get (url, params) {
    return axios({
      method: 'get',
      baseURL: baseUrl,
      url,
      params, // get 请求时带的参数
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  imgGet (url) {
    return axios({
      method: 'get',
      baseURL: baseUrl,
      url,
      responseType: 'blob',
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
